package com.jketing.controller.ams.base;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.jketing.controller.BaseController;
import com.jketing.entity.ams.base.Employee;
import com.jketing.entity.ams.base.Organ;
import com.jketing.service.ams.base.DictionaryService;
import com.jketing.service.ams.base.EmployeeService;
import com.jketing.service.ams.base.OrganService;
import com.jketing.utils.BeanUtil;
import com.jketing.utils.ImageUtil;

/**
 * Controller 请求处理
 * 
 * @author  李荣华
 * @version v1.0
 * @date    2017-11-22
 * @since   Spring-mvc 4.3.8
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController extends BaseController<Employee,String>{

	/**
	 *  service 服务层引用
	 */
	private EmployeeService service;
	/**
	 *  service 服务层自动注入
	 */
	@Autowired
	private OrganService os;
	/**
	 *  service 服务层自动注入
	 */
	@Autowired
	private DictionaryService ds;
	/**
	 *  service 自动注入服务层操作实例
	 */
	@Autowired
	public void setService(EmployeeService service) {
		super.setBaseService(service);
		this.service = service;
	}
	
	@Override
	protected String getPrefixPath() {
		return "base/employee/";
	}

	@Override
	protected String getQueryMode() {
		return "String";
	}
	
	@Override
	protected Employee getEntity(Employee entity) {
		entity.setCardType(null);
		entity.setDuty(null);
		entity.setEducationalBackground(null);
		entity.setNation(null);
		entity.setOrgan(null);
		entity.setQualification(null);
		entity.setSex(null);
		return entity;
	}
	
	/**
	 * 初始化单选对话框
	 */
	@Override
	protected void initSingleSelect(Map<String, Object> map) {
		List<Organ> list = os.getOrganList("unit");//加载单位列表
		map.put("list", list);
		map.put("topTree",os.getTree(service.getRootId()).toString());
	}

	/**
	 * 初始化多选对话框
	 */
	@Override
	protected void initMultiSelect(Map<String, Object> map) {
		List<Organ> list = os.getOrganList("unit");//加载单位列表
		map.put("list", list);
		map.put("topTree",os.getTree(service.getRootId()).toString());
	}
	
	/**
	 *  getEmployeeList 得到查询运算符
	 *  
	 *  ResponseBody注解直接向客户端返回Map,框架自动转化为json
	 *  
	 *  @return List<Employee>
	 */
	@RequestMapping(value="/getEmployeeList",method=RequestMethod.GET)
	@ResponseBody
    public List<Employee> getEmployeeList(String organId){
    	return os.getEmployeeList(organId);
    }
	
	/**
	 *  getOperateSelect 得到查询运算符
	 *  
	 *  ResponseBody注解直接向客户端返回Map,框架自动转化为json
	 *  
	 *  @return Map<String,String>
	 */
	@RequestMapping(value="/getOperateSelect",method=RequestMethod.GET)
	@ResponseBody
	public Map<String,String> getOperateSelect(String type){
		Map<String,String> map = BeanUtil.findOperators();
		if("String".equals(type)){
			map = BeanUtil.findOperatorsForString();
		}
		return map;
	}
	
	/**
	 *  getImage 得到图片二进制内容
	 *  
	 *  ResponseBody注解直接向客户端返回byte数组,框架自动转化为二进制流
	 *  
	 *  @param	String id:pk
	 *  
	 *  @return byte[]
	 */
	@RequestMapping(value="/getImage/{id}",method=RequestMethod.GET)
	@ResponseBody
	public byte[] getImage(@PathVariable("id") String id){
		Employee entity = service.findOne(id);
		return entity.getPhoto();
	}
	
	/**
	 * 初始化区域列表框架页
	 */
	@Override
	protected void initListFrame(Map<String, Object> map) {
		List<Organ> list = os.getOrganList("unit");//加载单位列表
		map.put("list", list);
		map.put("topTree", os.getTree((String)map.get("rootId")));//加载从id为根节点开始的树
	}
	
	@Override
	protected String getExpression(String expression) throws JsonProcessingException {
		String type = (String)getSession().getAttribute("employee_type");
		String nodeId = (String)request.getParameter("nodeId");
		if("redirect".equals(type)) {
			request.setAttribute("type", type);
			nodeId = getSession().getAttribute("employee_nodeId")!=null?getSession().getAttribute("employee_nodeId").toString():null;
			getSession().removeAttribute("employee_nodeId");
		}
		request.setAttribute("nodeId", nodeId);
		request.setAttribute("queryFields", toJson(BeanUtil.findQueryFields(Employee.class)));
		//可在此处增加修改查询条件的代码
		if(StringUtils.isNotBlank(expression)) {
			//query = "[Entity:organSet:Entity:unitNature:String:enName:=:unit]#";
			expression = expression.replace("#", "");
			expression = "[Entity:organs:String:id:=:" + nodeId + "]&(" + expression + ")#";
		}else {
			expression = "[Entity:organs:String:id:=:" + nodeId + "]#";
		}
		return expression;
	}
	
	/**
	 *  getQueryFields 得到实体动态查询字段
	 *  
	 *  ResponseBody注解直接向客户端返回Map,框架自动转化为json
	 *  
	 *  @return Map<String,String>
	 */
	@RequestMapping(value="/getQueryFields",method=RequestMethod.GET)
	@ResponseBody
	public Map<String,String> getQueryFields(){
		return BeanUtil.findQueryFields(Employee.class);
	}
	
	/**
	 *  初始化新增编辑页
	 */
	@Override
	protected void initAdd(Map<String, Object> map) {
		String nodeId = request.getParameter("nodeId");
		String expression = request.getParameter("expression");
		String order = request.getParameter("order");
		map.put("sex", ds.getPropertyByEnName("sex"));
		map.put("nation", ds.getPropertyByEnName("nation"));
		map.put("cardType", ds.getPropertyByEnName("cardType"));
		map.put("educationalBackground", ds.getPropertyByEnName("educationBackground"));
		map.put("qualification", ds.getPropertyByEnName("qualification"));
		map.put("duty", ds.getPropertyByEnName("duty"));
		map.put("ids", nodeId);
		map.put("names", os.findOne(nodeId).getName());
		//新增后返回所选树型节点列表
		getSession().setAttribute("employee_type", "redirect");
		getSession().setAttribute("employee_nodeId", nodeId);
		getSession().setAttribute("employee_query", expression);
		getSession().setAttribute("employee_order", order);
	}
	
	/**
	 *  初始化更新编辑页
	 */
	@Override
	protected void initEdit(Map<String, Object> map) {
		String nodeId = request.getParameter("nodeId");
		Employee entity = (Employee)map.get("entity");
		map.put("sex", ds.getPropertyByEnName("sex"));
		map.put("nation", ds.getPropertyByEnName("nation"));
		map.put("cardType", ds.getPropertyByEnName("cardType"));
		map.put("educationalBackground", ds.getPropertyByEnName("educationBackground"));
		map.put("qualification", ds.getPropertyByEnName("qualification"));
		map.put("duty", ds.getPropertyByEnName("duty"));
		map.put("organs",service.getOrgans(entity.getId()));
		//因更新后会重定向到列表，使用session保存翻页条件在多个请求中共享数据,基类已存		
		getSession().setAttribute("employee_nodeId", nodeId);
	}
	
	/**
	 *  保存前执行,用于保存之前再次设置要保存的实体属性或执行其它保存逻辑
	 * @throws IOException 
	 */
	@Override
	protected Employee beforeSave(Employee entity,MultipartFile file) throws IOException {
		String ids = request.getParameter("ids");
		if(file.getSize()>0) {
			entity.setPhoto(ImageUtil.getPhotoBytes(file, 512, 1027, 768));
		}
		setExecuteSave(false);//不执行基类的保存
		return service.save(entity,ids);
	}

	/**
	 *  更新前执行,用于更新之前再次设置要更新的实体属性或执行其它更新逻辑
	 */
	@Override
	protected Employee beforeUpdate(Employee entity,MultipartFile file) throws IOException {
		String ids = request.getParameter("ids");
		if(file.getSize()>0) {
			entity.setPhoto(ImageUtil.getPhotoBytes(file, 512, 1027, 768));
		}
		setExecuteSave(false);//不执行基类的保存
		return service.update(entity,ids);
	}
	
	@Override
	protected void beforeDeleting(List<String> ids) {
		String nodeId = request.getParameter("nodeId");
		//因删除后会重定向到列表，使用session保存翻页条件在多个请求中共享数据,基类已存query、order、page		
		getSession().setAttribute("employee_nodeId", nodeId);
	}
}
